#!/usr/bin/perl -w

# Copyright (C) 2015 Mark Schouten <mark@tuxis.nl>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2 dated June,
# 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# See http://www.gnu.org/licenses/gpl.txt for the full license

use constant {
    TIMEZONE => 'Europe/Amsterdam'
};

use strict;
use PVE::APIClient::LWP;
use PVE::AccessControl;
use PVE::INotify;
use Data::Dumper;

my $hostname = PVE::INotify::read_file("hostname");

my $ticket = PVE::AccessControl::assemble_ticket('root@pam');
my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token('root@pam');

my $conn = PVE::APIClient::LWP->new(
    ticket => $ticket,
    csrftoken => $csrftoken,
);

my $clustername;

foreach my $child (@{$conn->get("/api2/json/cluster/status")}) {
    if ($child->{'type'} eq "cluster") {
        $clustername = $child->{'name'};
    }
}

if (!defined($clustername)) {
        $clustername = $hostname;
}

print "<<<app-proxmox>>>\n";

print "$clustername\n";

foreach my $vm (@{$conn->get("/api2/json/nodes/$hostname/netstat")}) {
	my $vmid = $vm->{'vmid'};
    eval {
        my $vmname = $conn->get("/api2/json/nodes/$hostname/qemu/$vmid/config")->{'name'};
        my $tmpl = $conn->get("/api2/json/nodes/$hostname/qemu/$vmid/config")->{'template'};
        if (defined($tmpl) && $tmpl == 1) {
            die;
        }
        print "$vmid/$vm->{'dev'}/$vm->{'in'}/$vm->{'out'}/$vmname\n";
    };
    eval {
        my $vmname = $conn->get("/api2/json/nodes/$hostname/lxc/$vmid/config")->{'hostname'};
        my $tmpl = $conn->get("/api2/json/nodes/$hostname/lxc/$vmid/config")->{'template'};
        if (defined($tmpl) && $tmpl == 1) {
            die;
        }
        print "$vmid/$vm->{'dev'}/$vm->{'in'}/$vm->{'out'}/$vmname\n";
    };
};
